#!/usr/bin/python
'''
finds rna/scaffold pairs with a valid hairpin.
filters gff based on these pairs.
'''
import sys

# parameters.
hairpin_file = sys.argv[1]
gff_file = sys.argv[2]
out_file = sys.argv[3]

# read in pairs.
fin = open(hairpin_file)

# loop over file in chunks.
i = 0
sz = 0
chunk = 0
pairs = {}
while 1 == 1:
	# check if we need new chunk
	if i == sz:
		# read new chunk.
		lines = fin.readlines(100000000)
		sz = len(lines)
		i = 0
		chunk += 1
		print chunk, sz
		
	# check if we are done.
	if sz == 0: break
	
	# add to pair.
	tmp = lines[i].split("\t")
	
	if tmp[0] not in pairs:
		pairs[tmp[0]] = {}
		
	pairs[tmp[0]][tmp[1]] = True
	
	# increment pointer.
	i += 1
fin.close()
	
# open target gff.
fin = open(gff_file, "rb")
fout = open(out_file, "wb")

# loop over file in chunks.
i = 0
sz = 0
chunk = 0
pairs = {}
while 1 == 1:
	# check if we need new chunk
	if i == sz:
		# read new chunk.
		lines = fin.readlines(100000000)
		sz = len(lines)
		i = 0
		chunk += 1
		print chunk, sz
		
	# check if we are done.
	if sz == 0: break
	
	# add to pair.
	tmp = lines[i].split("\t")
	
	if tmp[0] in pairs and tmp[1] in pairs[tmp[0]]:
		fout.write(lines[i])
		
	# increment pointer.
	i += 1
	
fin.close()
fout.close()
